﻿using System.Linq;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace CustomWindows.Window_API
{
    class AlwaysOnTop: WindowsFunction
    {
        public enum WindowPos
        {
            SWP_NOMOVE = 0x0002,
            SWP_NOSIZE = 0x0001,
            TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE,
            HWND_BOTTOM = 1,
            HWND_TOP = 0,
            HWND_NOTOPMOST = -2,
            HWND_TOPMOST = -1
        }

		#region Fields (1) 

        //Rather than keep a list of OnTop IntPtr, I should get the properties of the window..
        private static readonly IList<IntPtr> AppList = new List<IntPtr>();

		#endregion Fields 

		#region Constructors (1) 

        public AlwaysOnTop(IntPtr hwnd) : base(hwnd)
        {
            Description = "AlwaysOnTop"; // ...Mike Cameron is gonna say something here
            EventLogger = new Event(DateTime.Now, Hwnd, Description);
        }

		#endregion Constructors 

		#region Methods (2) 

		// Public Methods (1) 

        public override void UpdateFunction()
        {
            IntPtr setPosHwnd;

            if ( AppExists())
            {
                setPosHwnd = (IntPtr) WindowPos.HWND_NOTOPMOST;
                AppList.Remove(Hwnd);
            }
            else
            {
                setPosHwnd = (IntPtr) WindowPos.HWND_TOPMOST;
                AppList.Add(Hwnd);
            }

            SetWindowPos(Hwnd, setPosHwnd, 0, 0, 0, 0, (uint)WindowPos.TOPMOST_FLAGS);
        }
		// Private Methods (1) 

        private bool AppExists()
        {
            return AppList.Any(x=> x ==Hwnd);
        }

		#endregion Methods 

        #region API

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
       
        #endregion
    }
}
